<template>
  <div class="movingEnd">
    <div class="header" />
    <User @click="userClick"
      style=" width: 30px; height: 30px; position: absolute; top: 5%; left: 5%; background-color: black; opacity: .5; color: aliceblue; border-radius: 50%;" />

    <div class="title">
      <div class="top">
        <div class="icon" />
        <div class="content">
          <div class="headline">菩提阁餐厅</div>
          <div class="text">
            <van-icon name="clock-o" color="#ffc500" style="margin: 0px 5px 0px 0px" /> 距您xxkm <van-icon name="balance-o"
              color="#ffc500" style="margin: 0px 5px 0px 10px" />配送费xx元 <van-icon name="underway-o" color="#ffc500"
              style="margin: 0px 5px 0px 10px" />预计时长xx分钟
          </div>
        </div>
      </div>

      <div class="intro">简介：菩提阁中餐厅是菩提阁点餐的独立的品牌，定位“大众”化的美食外送餐饮，旨为顾客打造专业美食</div>

    </div>

    <div class="main">
      <div class="tabsBox">
        <el-tabs v-model="activeName" tab-position="left" @tab-change="categoryChange" style="height: 100%">
          <el-tab-pane v-for="item in categoryData" :key="item.id" :name="item.id" :label="item.name" />
        </el-tabs>
      </div>

      <div class="dishes">
        <div class="dishesItem" v-for="item in dishData" :key="item.id">
          <el-image style="width: 100px; height: 100px" :src="item.url" fit="cover" />
          <div class="dishInfo">
            <div class="dishName">{{ item.name }}</div>
            <div class="describe">{{ item.description }}</div>
            <div class="sales">月销：0</div>
            <div class="priceBox">

              <div class="price">￥{{ (item.price) }}</div>

              <div v-if="item.btnShow">
                <el-button v-if="item.flavors && item.flavors.length" round color="#ffc500" size="small"
                  @click="selectionSpecification(item)">选择规格</el-button>
                <el-button v-else :icon="Plus" circle color="#ffc500" size="small" @click="addClick(item)"
                  style="margin-right: 10px;" />
              </div>

              <div v-else>
                <el-button :icon="SemiSelect" circle color="#fff" size="small" style="border: 1px solid #ffc500;" />

                <span style="margin: 0px 10px;">{{ item.count }}</span>

                <el-button :icon="Plus" circle color="#ffc500" size="small" @click="addClick(item)"
                  style="margin-right: 10px;" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="buttom" @click.stop="showShoppingCart">
      <el-image class="elImage" :src="require('@/assets/cart_active.png')" fit="cover" />

      <div class="totalValue">￥{{ totalMoney }}</div>

      <el-button round type="primary" color="#ffc500" :disabled="payBillDisabled" class="elButton"
        @click.stop="payBill">去结算</el-button>
    </div>

    <div v-if="shoppingCartShow" class="shoppingCartBox">
      <div class="titleBox" @click="clear">
        <div class="label">购物车</div>
        <div class="operation">
          <Delete style="width: 20px;" /> &nbsp;
          清空
        </div>
      </div>
      <hr />

      <div class="shoppingCartItem" v-for="(item) in shoppingCartArr" :key="item.id">
        <div class="leftBox">
          <el-image style="width: 70px; height: 70px" :src="item.url" fit="cover" />
          <div class="textBox">
            <div class="name">{{ item.name }}</div>
            <div class="price">￥{{ (item.amount) }}</div>
          </div>
        </div>

        <div class="operation">
          <el-button :icon="SemiSelect" circle color="#fff" size="small" style="border: 1px solid #ffc500;" />

          <span style="margin: 0px 10px;">{{ item.number }}</span>

          <el-button :icon="Plus" circle color="#ffc500" size="small"
            @click="saveShoppingCart(item), (item.number as number)++" style="margin-right: 10px;" />
        </div>
      </div>
    </div>

    <FlavorDialog v-model:centerDialogVisible="centerDialogVisible" v-model:currentDish="currentDish"
      @addCar="saveShoppingCart" />
  </div>
</template>

<script setup lang="ts" name="movingEnd">
import { onMounted, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getAllCategory, dishFlavorList, downloadImg, getSetmealList, addShoppingCart, shoppingCartList, clearShoppingCart } from '@/api/index'
import { Icategory, Idish, ISetmeal, IShoppingCart } from './interface/index'
import { ElMessage } from 'element-plus';
import { Plus, User, Delete, SemiSelect } from '@element-plus/icons-vue'
import FlavorDialog from './components/FlavorDialog.vue'

const router = useRouter()

onMounted(() => {
  initData()
  getShoppingCartData()
})

const activeName = ref('')
const categoryData = ref<Icategory[]>()
const setMealArr = ref<string[]>([])

const initData = async () => {
  try {
    const { data: categoryArr } = await getAllCategory<Icategory[]>()
    setMealArr.value = []
    categoryArr.forEach(item => {
      if (item.type == 2) {
        setMealArr.value.push(item.id)
      }
    })

    activeName.value = categoryArr[0].id
    categoryData.value = categoryArr
    // getDishData(categoryArr[0].id)


  } catch (error) {
    ElMessage.error(error as string)
  }
}

const getShoppingCartData = async () => {
  try {
    const { data } = await shoppingCartList<IShoppingCart[]>()
    if (data.length) {
      payBillDisabled.value = false

      data.forEach(async item => {
        item.url = await getImg(item.image)
        shoppingCartArr.value = data
      })
    } else {
      payBillDisabled.value = true
      shoppingCartArr.value = []
    }

  } catch (error) {
    ElMessage.error(error as string)
  }

}

const getImg = async (url: string) => {
  if (url) {
    const res = await downloadImg<Blob>({ name: url })
    // 使用 window.URL.createObjectURL 将图片流转为地址
    const path = window.URL.createObjectURL(new Blob([res as any], { type: 'image/png' }))
    return path
  }
}

// 获取菜品数据
const dishData = ref<Idish[] | ISetmeal[]>([])
const getDishData = async (id: string) => {
  try {
    const { data } = await dishFlavorList<Idish[]>({ categoryId: id })

    let i = 0
    if (!data.length) return dishData.value = []
    data.forEach(async item => {
      item.btnShow = true
      item.url = await getImg(item.image)
      i++
      if (i === data.length) {
        dishData.value = data
      }
    })

  } catch (error) {
    ElMessage.error(error as string)
  }
}

/**
 * 获取套餐数据
 * @param id 分类id
 */
const getSetmealData = async (id: string) => {
  try {
    const { data } = await getSetmealList<ISetmeal[]>({ categoryId: id })
    let i = 0
    if (!data.length) return dishData.value = []

    data.forEach(async item => {
      item.btnShow = true
      item.url = await getImg(item.image)
      i++
      if (i === data.length) {
        dishData.value = data
      }
    })
  } catch (error) {
    ElMessage.error(error as string)
  }
}
let type = ''
const categoryChange = (id: string) => {
  if (setMealArr.value.includes(id)) {
    type = 'setmealId'
    getSetmealData(id)
  } else {
    type = 'dishId'
    getDishData(id)
  }
}

const userClick = () => {
  router.push({ path: '/userIndex' })
}

const centerDialogVisible = ref(false)
const currentDish = ref<Idish | ISetmeal>({
  categoryId: '',
  code: '',
  createTime: '',
  createUser: '',
  description: '',
  id: '',
  image: '',
  isDeleted: -1,
  name: '',
  price: -1,
  sort: -1,
  status: -1,
  updateTime: '',
  updateUser: '',
  url: '',
  flavors: [],
  count: 0,
  btnShow: true
})

const selectionSpecification = (item: Idish) => {
  currentDish.value = item
  centerDialogVisible.value = true
}

const payBillDisabled = ref<boolean>(true)
const shoppingCartArr = ref<IShoppingCart[]>([])
// const totalMoney = ref<number>(0)


const addClick = (data: Idish | ISetmeal) => {
  const params: IShoppingCart = {
    name: data.name,
    image: data.image,
    [type]: data.id,
    amount: data.price,
  }

  saveShoppingCart(params)
}

const totalMoney = computed({
  get: () => {
    if (!shoppingCartArr.value.length) return 0
    let count = 0
    shoppingCartArr.value.forEach(item => {
      count += (item.amount * (item.number as number))
    })
    return (count)
  },

  set: (vale) => {
    return vale
  }
})

const shoppingCartShow = ref<boolean>(false)

const showShoppingCart = () => {
  shoppingCartShow.value = !shoppingCartShow.value
}

const payBill = () => {
  router.push('/confirmationPage')
}

const saveShoppingCart = async (data: IShoppingCart) => {
  try {
    const res = await addShoppingCart<IShoppingCart>(data)
    dishData.value.some(item => {
      if (item.id === (res.data.dishId || res.data.setmealId)) {
        item.count = res.data.number as number
        item.btnShow = false
      }
    })
    centerDialogVisible.value = false
    getShoppingCartData()
  } catch (error) {
    ElMessage.error(error as string)
  }
}

const clear = async () => {
  try {
    const { data } = await clearShoppingCart()
    getShoppingCartData()

  } catch (error) {
    ElMessage.error(error as string)
  }

}

</script>

<style scoped lang="scss">
.movingEnd {
  width: 100%;
  height: 100vh;
  position: relative;



  .header {
    width: 100%;
    height: 30vh;
    background: url('@/assets/mainBg.png') no-repeat;
    background-size: 100%;
  }

  .title {
    width: 92%;
    height: 18vh;
    position: absolute;
    top: 11%;
    left: 50%;
    transform: translate(-50%);
    border-radius: 10px;
    background-color: #fff;
    padding: 10px;

    .top {
      width: 100%;
      height: 60%;
      display: flex;

      .icon {
        min-width: 20%;
        height: 70%;
        background: url('@/assets/logo2.png') no-repeat;
        background-size: 100% 100%;
        background-position: 0px -5px;
        background-color: #333333;
        border-radius: 5px;
        margin-right: 20px;
      }

      .content {
        display: flex;
        flex-direction: column;

        .headline {
          font-size: 20px;
          margin-bottom: 10px;
        }
      }
    }

    .intro {
      font-size: 14px;
      color: darkgrey;
    }
  }

  .main {
    width: 100%;
    height: 60vh;
    position: relative;
    background-color: #f6f6f6;
    display: flex;


    .tabsBox {
      flex: 2
    }

    .dishes {
      flex: 8;
      overflow-y: auto;
      overflow-x: hidden;

      .dishesItem {
        display: flex;
        margin-bottom: 10px;
        padding-right: 10px;

        .dishInfo {
          width: calc(100% - 100px);
          margin-left: 20px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .dishName {
            font-size: 15px;
            font-weight: 700;
          }

          .describe {
            max-width: 100%;
            font-size: 13px;
            color: darkgrey;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
          }

          .sales {
            font-size: 13px;
            color: darkgrey;
          }

          .priceBox {
            font-size: 15px;
            font-weight: 700;
            display: flex;
            justify-content: space-between;

            .price {
              color: red;
            }
          }
        }
      }
    }
  }

  .buttom {
    z-index: 5;
    width: 90%;
    height: 40px;
    margin-left: 50%;
    margin-top: 10px;
    transform: translate(-50%);
    border-radius: 50px;
    background: #333333;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .elImage {
      position: absolute;
      top: -13px;
      left: 10px;
      height: 50px;
    }

    .totalValue {
      color: #fff;
      margin-left: 100px;
    }

    .elButton {
      width: 100px;
      height: 90%;
      margin-right: 3px;
    }
  }

  .shoppingCartBox {
    box-sizing: border-box;
    z-index: 3;
    position: absolute;
    bottom: 0px;
    width: 100%;
    height: 50%;
    background-color: #fff;
    padding: 10px 10px 50px 10px;
    overflow-y: auto;
    overflow-x: hidden;

    .titleBox {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .label {
        font-size: 18px;
        font-weight: 700;
      }

      .operation {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: #beb9b9;
      }
    }

    .shoppingCartItem {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;

      .leftBox {
        display: flex;

        .textBox {
          margin-left: 10px;
          font-weight: 700;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .price {
            color: red;
          }
        }
      }

      .operation {
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>